<template>
  <div>
    <!-- 新增查询企业名字输入框和按钮 -->
    <el-input
      v-model="search"
      placeholder="请输入企业名称"
      style="width: 200px; margin-right: 10px;"
    ></el-input>
    <el-button @click="searchMerchants" type="primary">查询</el-button>
    <el-button @click="resetSearch" type="primary">重置</el-button>
    <el-button type="success" @click="exportTable">导出表格</el-button>

    <el-table :data="list" style="width: 100%" ref="tableRef">
      <!-- 表格列 -->
      <el-table-column prop="merchant_id" label="企业编号"></el-table-column>
      <el-table-column prop="contacts" label="企业名称"></el-table-column>
      <el-table-column prop="business_term" label="营业期限"></el-table-column>
      <el-table-column prop="merchant_name" label="商户名字"></el-table-column>
      <el-table-column prop="merchant_type" label="经营类目"></el-table-column>

      <!-- 审核时间列，显示"未审核" -->
      <el-table-column label="审核时间">
        <template v-slot="scope">
          <span v-if="scope.row.review_time">{{ scope.row.review_time }}</span>
          <span v-else>未审核</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作">
        <template v-slot="scope">
          
          <!-- 查看详情按钮 -->
          <el-button @click="viewDetails(scope.row)" type="primary" size="small">查看详情</el-button>

          <!-- 切换合作状态按钮，显示当前合作状态 -->
          <el-button 
            @click="toggleCooperation(scope.row)" 
            :type="scope.row.collaboration_status === 1 ? 'danger' : 'success'" 
            size="small"
          >
            {{ scope.row.collaboration_status === 1 ? '暂停合作' : '恢复合作' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[ 5, 10,20, 100]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 抽屉 -->
    <el-drawer
      v-model="drawer"
      size="50%"
      direction="rtl"
      @close="clearOcrData"
    >
      <el-tabs v-model="tab">
        <el-tab-pane label="法人信息" name="1">
          <el-tag
            :type="selected.id_card_status === 1 ? 'success' : 'danger'"
            style="position: absolute; top: 5px; right: 5px;"
          >
            {{ selected.id_card_status === 1 ? '已通过' : '未通过' }}
          </el-tag>
          <div style="position: relative; display: inline-block; margin-right: 10px;">
            <el-image
              v-if="selected.front"
              :src="selected.front"
              :preview-src-list="[selected.front]"
              fit="contain"
              style="width: 60%; height: 150px; object-fit: contain; cursor: pointer;"
            ></el-image>
          </div>
          <div style="position: relative; display: inline-block;">
            <el-image
              v-if="selected.opposite"
              :src="selected.opposite"
              :preview-src-list="[selected.opposite]"
              fit="contain"
              style="width: 60%; height: 150px; object-fit: contain; cursor: pointer;"
            ></el-image>
          </div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ idCard.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ idCard.sex }}</el-descriptions-item>
            <el-descriptions-item label="民族">{{ idCard.ethnicity }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ idCard.address }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ idCard.idNumber }}</el-descriptions-item>
            <el-descriptions-item label="颁发机关">{{ idCard.issueAuthority }}</el-descriptions-item>
            <el-descriptions-item label="有效期限">{{ idCard.validPeriod }}</el-descriptions-item>
          </el-descriptions>
          <el-button @click="toggleIdCardStatus" :type="selected.id_card_status === 1 ? 'danger' : 'success'">
            {{ selected.id_card_status === 1 ? '切换为未通过' : '切换为已通过' }}
          </el-button>
        </el-tab-pane>
        <el-tab-pane label="营业执照" name="2">
          <el-tag
            :type="selected.business_status === 1 ? 'success' : 'danger'"
            style="position: absolute; top: 5px; right: 5px;"
          >
            {{ selected.business_status === 1 ? '已通过' : '未通过' }}
          </el-tag>
          <el-image
            v-if="selected.image"
            :src="selected.image"
            :preview-src-list="[selected.business_license]"
            fit="contain"
            style="width: 50%;height: 250px; object-fit: contain; cursor: pointer;"
          ></el-image>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="统一社会信用代码">{{ business.creditCode }}</el-descriptions-item>
            <el-descriptions-item label="企业名称">{{ business.companyName }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ business.companyType }}</el-descriptions-item>
            <el-descriptions-item label="法定代表人">{{ business.legalPerson }}</el-descriptions-item>
            <el-descriptions-item label="注册资本">{{ business.registeredCapital }}</el-descriptions-item>
            <el-descriptions-item label="成立日期">{{ business.RegistrationDate }}</el-descriptions-item>
            <el-descriptions-item label="营业期限">{{ business.validPeriod }}</el-descriptions-item>
            <el-descriptions-item label="经营范围">{{ business.businessScope }}</el-descriptions-item>
          </el-descriptions>
          <el-button @click="toggleAuditStatus" :type="selected.business_status === 1 ? 'danger' : 'success'">
            {{ selected.business_status === 1 ? '切换为未通过' : '切换为已通过' }}
          </el-button>
        </el-tab-pane>
        <el-tab-pane label="其他资质" name="3">
          <el-image
            v-if="selected.other_qualifications"
            :src="selected.other_qualifications"
            :preview-src-list="[selected.business_license]"
            fit="contain"
            style="width: 100%;height: 250px; object-fit: contain; cursor: pointer;"
          ></el-image>
        </el-tab-pane>
        <el-tab-pane label="开户信息" name="4">
          <el-tag
            :type="selected.accounts_status === 1 ? 'success' : 'danger'"
            style="position: absolute; top: 5px; right: 5px;"
          >
            {{ selected.accounts_status === 1 ? '已通过' : '未通过' }}
          </el-tag>
          <el-image
            v-if="selected.imgs"
            :src="selected.imgs"
            :preview-src-list="[selected.imgs]"
            fit="contain"
            style="width: 60%; height: 300px; object-fit: contain; cursor: pointer;"
          ></el-image>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="存款编号">{{ account.approvalNumber }}</el-descriptions-item>
            <el-descriptions-item label="单位名称">{{ account.customerName }}</el-descriptions-item>
            <el-descriptions-item label="开户银行">{{ account.depositaryBank }}</el-descriptions-item>
            <el-descriptions-item label="账号">{{ account.bankAccount }}</el-descriptions-item>
            <el-descriptions-item label="法人名称">{{ account.legalRepresentative }}</el-descriptions-item>
          </el-descriptions>
          <el-button @click="toggleAccountsStatus" :type="selected.accounts_status === 1 ? 'danger' : 'success'">
            {{ selected.accounts_status === 1 ? '切换为未通过' : '切换为已通过' }}
          </el-button>
        </el-tab-pane>
      </el-tabs>

      <div style="margin-top: 20px; text-align: right;">
        <!-- 审核通过按钮 -->
        <el-button type="success" @click="auditMerchantPass">审核通过</el-button>
        <!-- 审核不通过按钮 -->
        <el-button type="danger" @click="showReviewDialog">审核不通过</el-button>
      </div>
    </el-drawer>

    <!-- 审核意见弹窗 -->
    <el-dialog
      v-model="reviewDialog"
      title="请输入审核意见"
      width="30%"
      @close="reviewComments = ''"
    >
      <el-input
        v-model="reviewComments"
        type="textarea"
        rows="4"
        placeholder="请输入审核意见"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialog = false">取消</el-button>
          <el-button type="primary" @click="auditMerchantReject">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getMerchant, insertOrUpdateMerchant, getRecognizeIdCard, InsertOrUpdateIdCard, insterOrUpdateBusiness, insterOrUpdateAccounts, recognizeBusinessLicense, recognizeBankAccountLicense } from '@/api/admin';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { useTokenStore } from '@/stores/token';
import * as XLSX from 'xlsx';

// 定义变量
const uts = useTokenStore();
const router = useRouter();
// 商户列表数据
const list = ref([]);
const page = ref(1);
const size = ref(10);
const total = ref(0);
// 控制抽屉显示
const drawer = ref(false);
// 选中的商户信息
const selected = ref({});
// 当前选中的标签页
const tab = ref('1');
// 控制审核意见弹窗显示
const reviewDialog = ref(false);
// 审核意见内容
const reviewComments = ref('');
// 搜索关键词
const search = ref(''); 
const idCard = ref({});
const business = ref({});
const account = ref({});
// 表格引用
const tableRef = ref();

// 表格导出
const exportTable = () => {
  const data = list.value.map(item => ({
    '企业编号': item.merchant_id,
    '企业名称': item.contacts,
    '营业期限': item.business_term,
    '商户名字': item.merchant_name,
    '经营类目': item.merchant_type,
    '审核时间': item.review_time || '未审核'
  }));

  const ws = XLSX.utils.json_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "商户列表");
  XLSX.writeFile(wb, "商户列表.xlsx");
};

// 获取身份证OCR识别结果
const fetchOcrResults = async (front, opposite) => {
  try {
    const response = await getRecognizeIdCard({ frontImageUrl: front, backImageUrl: opposite });
    console.log(response);
    if (response.shuju) {
      // 解析OCR结果
      const frontData = JSON.parse(response.shuju.frontOcrResult);
      const frontData2 = JSON.parse(frontData.body.data);
      const backData = JSON.parse(response.shuju.backOcrResult);
      const backData2 = JSON.parse(backData.body.data);
      
      // 设置OCR结果
      idCard.value = {
        name: frontData2.data.face.data.name,
        sex: frontData2.data.face.data.sex,
        ethnicity: frontData2.data.face.data.ethnicity,
        address: frontData2.data.face.data.address,
        idNumber: frontData2.data.face.data.idNumber,
        issueAuthority: backData2.data.back.data.issueAuthority,
        validPeriod: backData2.data.back.data.validPeriod,
      };
    } else {
      console.error('OCR识别失败：没有返回数据');
      ElMessage.error('身份证OCR识别失败，请检查图片质量并重试');
    }
  } catch (error) {
    console.error('OCR识别过程中发生错误:', error);
    ElMessage.error('身份证OCR识别出错，请稍后重试或联系技术支持');
  }
};

// 获取营业执照OCR识别结果
const fetchBusinessOcrResults = async (image) => {
  try {
    const response = await recognizeBusinessLicense({ imageUrl: image });
    if (response.shuju) {
      const data = JSON.parse(response.shuju.recognitionResult);
      const businessData = JSON.parse(data.body.data);
      
      business.value = {
        creditCode: businessData.data.creditCode,
        companyName: businessData.data.companyName,
        companyType: businessData.data.companyType,
        legalPerson: businessData.data.legalPerson,
        registeredCapital: businessData.data.registeredCapital,
        RegistrationDate: businessData.data.RegistrationDate,
        validPeriod: businessData.data.validPeriod,
        businessScope: businessData.data.businessScope,
      };
    } else {
      console.error('营业执照OCR识别失败：没有返回数据');
      ElMessage.error('营业执照OCR识别失败，请检查图片质量并重试');
    }
  } catch (error) {
    console.error('营业执照OCR识别过程中发生错误:', error);
    ElMessage.error('营业执照OCR识别出错，请稍后重试或联系技术支持');
  }
};

// 获取开户许可证OCR识别结果
const fetchAccountOcrResults = async (image) => {
  try {
    const response = await recognizeBankAccountLicense({ imageUrl: image });
    if (response.shuju) {
      const data = JSON.parse(response.shuju.recognitionResult);
      const accountData = JSON.parse(data.body.data);
      
      account.value = {
        approvalNumber: accountData.data.approvalNumber,
        customerName: accountData.data.customerName,
        depositaryBank: accountData.data.depositaryBank,
        bankAccount: accountData.data.bankAccount,
        legalRepresentative: accountData.data.legalRepresentative,
      };
    } else {
      console.error('开户许可证OCR识别失败：没有返回数据');
      ElMessage.error('开户许可证OCR识别失败，请检查图片质量并重试');
    }
  } catch (error) {
    console.error('开户许可证OCR识别过程中发生错误:', error);
    ElMessage.error('开户许可证OCR识别出错，请稍后重试或联系技术支持');
  }
};

// 获取商户列表
const fetchMerchants = async () => {
  if (uts.token.id === undefined) {
    console.error('未登录或登录已过期');
    ElMessage.error('请先登录');
    router.push('/admin');
    return;
  }
  try {
    const response = await getMerchant({
      pageNo: page.value,
      pageSize: size.value
    });
    
    if (response.flag) {
      console.log(response);
      list.value = response.shuju.merchants || [];
      total.value = response.shuju.total || 0;
      uts.mergeTokenWithData(response.shuju);
      console.log('当前用户ID:', uts.token.id);
    } else {
      ElMessage.warning(response.message || '获取商户列表失败');
    }
  } catch (error) {
    console.error('获取商户信息失败:', error);
    ElMessage.error('获取商户信息时发生错误，请稍后重试');
  } finally {
  }
};

// 搜索商户
const searchMerchants = async () => {
  try {
    const response = await getMerchant({
      pageNo: 1,
      pageSize: size.value,
      contacts: search.value 
    });
    
    if (response.flag) {
      list.value = response.shuju.merchants || [];
      total.value = response.shuju.total || 0;
      page.value = 1;
      uts.mergeTokenWithData(response.shuju);
    }
  } catch (error) {
    console.error('查询商户信息失败:', error);
  }
};

// 重置搜索
const resetSearch = () => {
  search.value = '';
  fetchMerchants();
};
// 查看商户详情
const viewDetails = async (row) => {
  selected.value = row;
  await fetchOcrResults(row.front, row.opposite);
  await fetchBusinessOcrResults(row.image);
  await fetchAccountOcrResults(row.imgs);
  drawer.value = true;
  tab.value = '1';
};

// 清除OCR识别到的数据
const clearOcrData = () => {
  idCard.value = {};
  business.value = {};
  account.value = {};
};

// 显示审核对话框
const showReviewDialog = () => {
  reviewComments.value = '';
  reviewDialog.value = true;
};

// 审核商户通过
const auditMerchantPass = async () => {
  const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
  // 检查三个审核状态是否都通过
  if (selected.value.id_card_status !== 1) {
    ElMessage.error('请确保身份证信息已通过审核');
    return;
  }
  if (selected.value.business_status !== 1) {
    ElMessage.error('请确保营业执照信息已通过审核');
    return;
  }
  if (selected.value.accounts_status !== 1) {
    ElMessage.error('请确保开户信息已通过审核');
    return;
  }
  try {
    const response = await insertOrUpdateMerchant({
      ...selected.value,
      auditStatus: 1,
      reviewTime: now,
      reviewComments: '',
      reviewedBy: uts.token.id
    });

    if (response.flag) {
      console.log('审核状态更新成功');
      drawer.value = false;
      fetchMerchants();
      ElMessage.success('商户审核通过');
    } else {
      console.error('审核状态更新失败');
      ElMessage.error('审核状态更新失败，请重试');
    }
  } catch (error) {
    console.error('更新审核状态时发生错误:', error);
    ElMessage.error('更新审核状态时发生错误，请重试');
  }
};

// 审核商户不通过
const auditMerchantReject = async () => {
  const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
  try {
    const response = await insertOrUpdateMerchant({
      ...selected.value,
      auditStatus: 2,
      reviewTime: now,
      reviewComments: reviewComments.value,
      reviewedBy: uts.token.id
    });
    if (response.flag) {
      console.log('审核状态更新成功');
      reviewDialog.value = false;
      drawer.value = false;
      fetchMerchants();
    } else {
      console.error('审核状态更新失败');
    }
  } catch (error) {
    console.error('更新审核状态时发生错误:', error);
  }
};

// 切换商户合作状态
const toggleCooperation = async (row) => {
  if(row.audit_status==2&&row.collaboration_status==0){
    ElMessage.error('审核未通过，无法合作');
    return;
    }
  const newStatus = row.collaboration_status === 1 ? 0 : 1;
  row.collaboration_status = newStatus;
  
  try {
    const response = await insertOrUpdateMerchant({
      ...row,
      collaborationStatus: newStatus  
    });
    if (response.flag) {
      console.log('合作状态更新成功');
    } else {
      console.error('合作状态更新失败');
    }
  } catch (error) {
    console.error('更新合作状态时发生错误:', error);
  }
};

// 切换身份证审核状态
const toggleIdCardStatus = async () => {
  const newStatus = selected.value.id_card_status === 1 ? 0 : 1;
  try {
    const response = await InsertOrUpdateIdCard({
      ...selected.value,
      status: newStatus
    });
    if (response.flag) {
      selected.value.id_card_status = newStatus;
      console.log('身份证审核状态更新成功');
    } else {
      console.error('身份证审核状态更新失败');
    }
  } catch (error) {
    console.error('更新身份证审核状态时发生错误:', error);
  }
};

// 切换营业执照审核状态
const toggleAuditStatus = async () => {
  const newStatus = selected.value.business_status === 1 ? 0 : 1;
  try {
    const response = await insterOrUpdateBusiness({
      ...selected.value,
      auditStatus: newStatus
    });
    if (response.flag) {
      selected.value.business_status = newStatus;
      console.log('营业执照审核状态更新成功');
    } else {
      console.error('营业执照审核状态更新失败');
    }
  } catch (error) {
    console.error('更新营业执照审核状态时发生错误:', error);
  }
};

// 切换开户信息审核状态
const toggleAccountsStatus = async () => {
  const newStatus = selected.value.accounts_status === 1 ? 0 : 1;
  try {
    const response = await insterOrUpdateAccounts({
      ...selected.value,
      status: newStatus
    });
    if (response.flag) {
      selected.value.accounts_status = newStatus;
      console.log('开户信息审核状态更新成功');
    } else {
      console.error('开户信息审核状态更新失败');
    }
  } catch (error) {
    console.error('更新开户信息审核状态时发生错误:', error);
  }
};

// 处理页面大小变化
const handleSizeChange = (val) => {
  size.value = val;
  page.value = 1;
  fetchMerchants();
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  page.value = val;
  fetchMerchants();
};

// 组件挂载时获取商户列表
onMounted(() => {
  fetchMerchants();
});
</script>

<style scoped>
.el-button.success {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}
.el-button.danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

</style>
